<?php
/*************************************
 *
 * @Controller 控制层主要接收与传递参数
 *
 ************************************/
namespace app\api\controller;

use app\common\services\UserServices;

use app\common\services\ImageServices;

use app\common\services\CodeMaServices;

use think\Env;

use think\Request;

use think\Response;

use think\config;
use \think\exception\HttpException;

class User extends Base
{
    protected $UserServices;

    protected $timeout = 10;

    protected $Request;

    public function __construct
    (
        Request $request
    )
    {
        parent::__construct($request);
        $this->UserServices = new UserServices();
    }
    /**
     *  登录
     */
    public function login(Request $request)
    {
        $respons = $request->param();
        $check = $this->checkOust($respons);
        if (is_array($check)) {
            return $this->errorHttpResult(['data'=>$check['data'], 'status_code' => 400], 400);
        }
        //根据code获取session_key以及openid
        $wxSession =  $this->UserServices->getWechatInfoByCode($respons);
        $wxSession = json_decode($wxSession,true);
        if (!isset($wxSession['session_key'])) {
            return $this->errorHttpResult(['data'=>$wxSession, 'status_code' => 400], 400);
        }
        if (is_array($wxSession)) {
            //保存或更新用户
            $wx_session = $this->UserServices->regist($wxSession, $respons);
            if ($wx_session) {
                return json(['session_key' => $wx_session, 'status_code'=>200],200);
            } else {
                return $this->errorHttpResult(['data'=>'api.error.user', 'status_code' => 400], 400);
            }
        } else {
            return $this->errorHttpResult(['data'=>'api.error.wxerror', 'status_code' => 400], 400);
        }
    }

    /*
     *  提交订单
     *  @param String session_key
     */
    public function addOrder(Request $request)
    {
        if(!Request::instance()->isPost()) {
            return json(['msg' => '非法请求！', 'status_code'=>400]);
        }
        $respons = $request->param();
        $check = $this->checkOust($respons);
        if (is_array($check)) {
            return $this->errorHttpResult(['data'=>$check['data'], 'status_code' => 400], 400);
        }
        $sessionKey = $respons['session_key'];
        $checkLogin = $this->UserServices->checkLogin($sessionKey);
        if (!$checkLogin) {
            return json(['msg' => '暂未登陆', 'status_code'=>400]);
        }
        $respons['user_id'] = $checkLogin['id'];
        $msg = $this->UserServices->addOrder($respons);

        if ($msg) {
            return json(['msg' => '添加成功', 'status_code'=>200]);
        }
        return json(['msg' => '添加失败', 'status_code'=>400]);
    }

    /*
     *  短信接口
     */
    public function sendMsg(Request $request)
    {
        if(!Request::instance()->isPost()) {
            return json(['msg' => '非法请求！', 'status_code'=>400]);
        }
        $respons = $request->param();
//        $check = $this->checkOust($respons);
//        if (is_array($check)) {
//            return $this->errorHttpResult(['data'=>$check['data'], 'status_code' => 400], 400);
//        }
        $code = rand(1000, 9999);
        //短信
        $post_data = array();
        $post_data['account'] = "xumx_lz";
        $post_data['pswd'] = "Lz123456";
        $post_data['mobile'] = $respons['mobile'];
        $post_data['msg']= "【神行旅社】验证码".$code.":,请在10分钟内按页面提示提交验证码,切勿将验证码泄露于他人。";
        $post_data['needstatus'] ="true";
        $url='http://118.178.188.81/msg/HttpBatchSendSM';
        $o="";
        $data['mobile'] = $respons['mobile'];
        $data['code'] = $code;
        $data['smsbody'] = $post_data['msg'];
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $r= curl_exec($ch);
        if ($r) {
            $data['status'] = 2;
            $data['send_time'] = time();
            $this->UserServices->saveCode($data);
            return json(['msg' => '发送成功', 'status_code'=>200]);
        }
        return json(['msg' => '发送失败', 'status_code'=>400]);
    }

    /**
     *  获取小程序二维码
     */
    public function getCode()
    {
        header('Content-type: image/jpeg');
        $path = Env::get('XCXAPPKEY.wxpath');
        $width = 430;
        $uid = 6;
        $data = array();
        $data['scene'] = "uid=" . $uid;
        $accessToken =  $this->CodeMaServices->getAccessToken();
        $data['path'] = $path;
        $data = json_encode($data, true);

        //菊花码
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $accessToken;
        $request = $this->CodeMaServices->https_request($url, $data);
        //普通二维码
//        $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$accessToken}";
//        $request = $this->CodeMaServices->https_request($url, $data);
        $savename = md5($url);
        $path = ROOT_PATH .'Uploads/code/'.$savename.'.jpeg';
        $fh = fopen($path, 'w');
        flock($fh, LOCK_EX);
        fwrite($fh, $request);
        flock($fh, LOCK_UN);
        fclose($fh);
        $this->successResult('200', ['path' => $path]);
    }
    /**
     * 图片地址替换成压缩URL
     * @param string $content 内容
     * @param string $suffix 后缀
     */
    function get_img_thumb_url($content="",$suffix="!c550x260.jpg")
    {
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img src="${1}'.$suffix.'" style="max-width:100%">', $content);
        return $content;
    }

    /**
     * 获取当日心情
     * @param int id 主键ID
     * @return JSON
     */
    public function getInfo(Request $request)
    {
        $respons = $request->param();
        if (!$respons) {
            return $this->errorHttpResult(['data'=>'参数错误!', 'status_code' => 400], 400);
        }
        $msg =  $this->UserServices->getInfo($respons);
        if ($msg) {
            $this->successResult('200', $msg);
        } else {
            return $this->errorHttpResult(['data'=>'暂无数据!', 'status_code' => 404], 404);
        }
    }

    /**
     * 新增用户信息
     * @param int id 主键ID
     * @return JSON
     */
    public function saveInfo(Request $request)
    {

        $respons = $request->param();
        //过滤敏感词汇
        $pathTest = __VENDOR__ . 'lustre/phpsensitive/tests/data/words.txt';
        $handle = SensitiveHelper::init()->setTreeByFile($pathTest);
        $islegal = $handle->islegal($respons['mood']);
        if ($islegal) {
            $filterContent = $handle->replace($respons['mood'], '***');
            $respons['mood'] = $filterContent;
        }
        $file = $request->file('img');
        //过滤微信表情
        $value = json_encode($respons['mood']);
        $value = preg_replace("/\\\u[ed][0-9a-f]{3}\\\u[ed][0-9a-f]{3}/","*",$value);//替换成*
        $value = json_decode($value);
        $moodEmoji = str_replace('*', '',$value);
        if (!$file) {
            $nameFile = $respons['img'];
            $this->ImageServices->imageWriteText($nameFile, $moodEmoji, $nameFile, $respons['user_id']);
            $id = $this->UserServices->addInfo($respons);
        } else {
            $nameFile = $file->getInfo();
            $config = Config::get('UPLOAD_JFIMG_CONFIG');
            $client = new jfuploads($config['ak'], $config['sk'], 'https://imgserver-api.20hn.cn/v1');
            try {
                // 文件上传
                $response = $client->upload($nameFile['tmp_name']);
                // http 响应状态码
                echo $response->getStatusCode();
                // http 请求返回内容
                $obj = $response->getBody();
                $arr  = json_decode((string)$obj);
                if ($arr->url) {
                    //文字写入图片处理
                    $shareImgFile = $this->ImageServices->imageWriteText($nameFile['tmp_name'], $moodEmoji, $arr->url, $respons['user_id']);
                    $respons['img'] = $arr->url;
                    $id = $this->UserServices->addInfo($respons);
                }
            } catch (GuzzleHttp\Exception\BadResponseException $e) {
                // 4xx 或 5xx 错误
                $response = $e->getResponse();
                echo $response->getStatusCode();
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
        //自动验证返回规则
        if (is_array($id) && isset($id['check'])) {
            return $this->errorHttpResult(['data'=>$id['check'], 'status_code' => 400], 400);
        }
        if (is_numeric($id)){
            $retrunData['id'] = $id;
            if (isset($respons['img'])) {
                $retrunData['img'] = $respons['img'];
            }
            $retrunData['create_time'] = $respons['create_time'];
            $this->successResult('200',  $retrunData);
        } elseif (is_string($id)) {
            return $this->errorHttpResult(['data'=>'心情不能为空哦!', 'status_code' => 400], 400);
        } else {
            return $this->errorHttpResult(['data'=>'创建失败!', 'status_code' => 400], 400);
        }
    }

    /*
     *   获取个人列表
     *   @param int time 时间戳
     */
    public function getListMood(Request $request)
    {
        $param = $request->param();
        $msg = $this->UserServices->getListMood($param);
        if (is_string($msg)) {
            return $this->errorHttpResult(['data'=>$msg, 'status_code' => 400], 400);
        }
        if ($msg) {
            $this->successResult('200',  $msg);
        } else {
            return $this->errorHttpResult(['data'=>'暂无数据！', 'status_code' => 404], 404);
        }
    }

    /*
    *   点赞功能
    *   @param String sgin 数据标识
    *   @param Int id 数据id
    *   @param Int user_id 用户id
    *   @param Int click 点赞量
    */
    public function click(Request $request)
    {
        $param = $request->param();
        $msg = $this->UserServices->click($param);
        if ($msg == 400) {
            return $this->errorHttpResult(['data'=>'点赞失败！', 'status_code' => 400], 400);
        } elseif(is_array($msg)) {
            $this->successResult(200, $msg);
        } elseif (is_string($msg)) {
            return $this->errorHttpResult(['data'=>$msg, 'status_code' => 400], 400);
        }
    }
}